/**
 * 
 */
package org.lightcommons.orm.hibernate;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.lightcommons.orm.DaoFactory;
import org.lightcommons.orm.Dao;

/**
 * @author gl
 * @since Jun 15, 2008
 */
public class HibernateDaoFactory implements DaoFactory{

	private final HibernateDaoTemplate hibernateDaoTemplate;
	private final Map<Class<?>, Dao<?, ?>> daoCache;
	/**
	 * @param hibernateDaoTemplate
	 */
	public HibernateDaoFactory(HibernateDaoTemplate hibernateDaoTemplate) {
		super();
		this.hibernateDaoTemplate = hibernateDaoTemplate;
		this.daoCache = new HashMap<Class<?>, Dao<?,?>>();
	}

	public HibernateDaoFactory(SessionHolder sessionHolder){
		this(new HibernateDaoTemplate(sessionHolder));
	}
	
	/**
	 * 
	 */
	public HibernateDaoFactory(SessionFactory sessionFactory) {
		this(new ThreadLocalSessionHolder(sessionFactory));
	}
	
	/* (non-Javadoc)
	 * @see org.lightcommons.orm.DaoFactory#getDaoOf(java.lang.Class)
	 */
	public <T, ID extends Serializable> Dao<T, ID> getDaoOf(Class<T> entityClass) {
		Dao<T, ID> dao = (Dao<T, ID>) daoCache.get(entityClass);
		if(dao == null){
			dao = new HibernateDao<T, ID>(hibernateDaoTemplate,entityClass,null);
			daoCache.put(entityClass, dao);
		}
		return dao;
	}
	
}
